Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logging #143

Merged
merged 6 commits into from
Oct 15, 2024
Merged

Add logging #143

merged 6 commits into from
Oct 15, 2024

Conversation

ryardley
Copy link
Contributor

@ryardley ryardley commented Oct 10, 2024

Closes: #124

  • add tracing crate
  • replace println with tracing::xxxx() where apprpriate

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced logging capabilities across multiple components using structured logging with the tracing crate.
    • New asynchronous handling for ciphertext decryption in the Keyshare actor.
    • Added new methods for improved error handling and event management in various modules.
  • Bug Fixes

    • Improved error handling in event processing to provide clearer messages and prevent duplicate event submissions.
  • Documentation

    • Updated comments and documentation to reflect changes in method signatures and functionality.
  • Tests

    • Expanded test cases to ensure robust event handling and data integrity across the system.
    • Added new tests for the P2P actor to validate event forwarding behavior.

Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

Walkthrough

This pull request introduces several enhancements across multiple packages, primarily focusing on integrating the tracing crate for improved logging and error handling. Key changes include the addition of structured logging in various components, the implementation of new methods for better event handling, and updates to the Cargo.toml files to include new dependencies. Additionally, several test cases have been enhanced to validate the functionality and robustness of the event handling mechanisms.

Changes

File Path Change Summary
packages/ciphernode/aggregator/Cargo.toml Added dependency: tracing = { workspace = true }.
packages/ciphernode/aggregator/src/plaintext_aggregator.rs Integrated tracing for error logging; updated add_share and set_decryption methods to return the aggregator's state.
packages/ciphernode/aggregator/src/publickey_aggregator.rs Integrated tracing for error logging in the handle method.
packages/ciphernode/core/src/events.rs Modified fmt::Display for EventId; added get_data method to EnclaveEvent; added Display implementations for various structs; expanded EnclaveErrorType enum with Sortition.
packages/ciphernode/enclave/Cargo.toml Added dependencies: tracing-subscriber = { workspace = true }, tracing = { workspace = true }.
packages/ciphernode/enclave/src/bin/aggregator.rs Replaced println! with info! for logging; initialized tracing_subscriber.
packages/ciphernode/enclave/src/main.rs Replaced println! with info! for logging; initialized tracing_subscriber.
packages/ciphernode/enclave_node/src/main.rs Deleted file containing main entry point for the enclave.
packages/ciphernode/evm/Cargo.toml Added dependency: tracing = { workspace = true }.
packages/ciphernode/evm/src/ciphernode_registry_sol.rs Integrated tracing for structured logging; updated error handling in extractor function.
packages/ciphernode/evm/src/enclave_sol_reader.rs Integrated tracing for structured logging; updated error handling in extractor function.
packages/ciphernode/evm/src/enclave_sol_writer.rs Replaced println! with info! for logging transaction hashes.
packages/ciphernode/evm/src/helpers.rs Added logging functionality in stream_from_evm function using tracing.
packages/ciphernode/evm/src/registry_filter_sol.rs Replaced println! with info! for logging transaction hashes.
packages/ciphernode/keyshare/src/keyshare.rs Added asynchronous handler for CiphertextOutputPublished event; updated error handling in handle method.
packages/ciphernode/logger/Cargo.toml Added dependency: tracing = { workspace = true }.
packages/ciphernode/p2p/src/libp2p_router.rs Integrated tracing for structured logging; added asynchronous start method.
packages/ciphernode/p2p/src/p2p.rs Added spawn_libp2p method; improved error handling in handle methods.
packages/ciphernode/router/Cargo.toml Added dependencies: anyhow = { workspace = true }, tracing = { workspace = true }.
packages/ciphernode/router/src/ciphernode_selector.rs Added logging for ciphernode selection failures.
packages/ciphernode/router/src/hooks.rs Enhanced error handling using anyhow for various structs.
packages/ciphernode/sortition/Cargo.toml Added dependency: tracing = { workspace = true }.
packages/ciphernode/sortition/src/sortition.rs Updated contains method to return Result<bool>; added bus field to Sortition struct.
packages/ciphernode/test_helpers/Cargo.toml Added dependency: tracing = { workspace = true }.
packages/ciphernode/test_helpers/src/plaintext_writer.rs Updated logging in handle method to use info!.
packages/ciphernode/test_helpers/src/public_key_writer.rs Updated logging in handle method to use info!.
packages/ciphernode/test_helpers/src/utils.rs Added logging in write_file_with_dirs function.
packages/ciphernode/tests/tests/test_aggregation_and_decryption.rs Enhanced test cases and logic for event handling and decryption share generation.
tests/basic_integration/test.sh Added export RUST_LOG=info to set logging level.

Assessment against linked issues

Objective Addressed Explanation
Use the tracing crate (#[124])
Pass e3_id to all logs to enable filtering (#[124]) Not all logs include e3_id as required.

Possibly related PRs

Suggested reviewers

  • samepant
  • nginnever
  • auryn-macmillan
  • hmzakhalid

🐇 In the land of code where rabbits play,
New logs are hopping in a structured way.
With tracing in tow, errors now shine,
Our functions are spry, and all will be fine!
So gather 'round, friends, let's cheer and rejoice,
For clearer logs now give us a voice! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Outside diff range and nitpick comments (46)
packages/ciphernode/test_helpers/Cargo.toml (1)

16-16: LGTM! Consider adding features for tracing.

The addition of the tracing dependency is appropriate and aligns with the PR objectives to enhance logging capabilities. This change will allow the use of structured logging in the test helpers, which can significantly improve debugging and observability during testing.

Consider specifying any specific features of the tracing crate that you intend to use. For example, if you plan to use the log compatibility layer, you could modify the dependency like this:

tracing = { workspace = true, features = ["log"] }

This can help to explicitly document which features of tracing are being used in the test helpers.

packages/ciphernode/sortition/Cargo.toml (1)

18-18: LGTM! Consider specifying features for tracing.

The addition of the tracing crate as a workspace dependency is a good step towards improving logging capabilities, which aligns well with the PR objectives. This change will enable structured, contextual, and async-aware logging in the sortition package.

Consider specifying the features you intend to use from the tracing crate. This can help optimize compile times and binary size. For example:

tracing = { workspace = true, features = ["attributes"] }

Replace ["attributes"] with the specific features you need. If you're unsure which features to include, you can leave it as is for now and optimize later when you have a better understanding of your logging requirements.

packages/ciphernode/enclave/Cargo.toml (1)

17-18: LGTM! Consider adding version constraints.

The addition of tracing and tracing-subscriber dependencies aligns well with the PR objectives to enhance logging functionality. Using workspace = true ensures consistent versioning across the workspace, which is a good practice.

Consider adding version constraints to these dependencies in the workspace Cargo.toml file if they're not already present. This helps ensure reproducible builds and easier upgrades in the future.

packages/ciphernode/test_helpers/src/utils.rs (2)

12-15: LGTM: Good addition of structured logging with error handling.

The match statement effectively logs the path being written to and handles the case where the path can't be converted to a string. The use of trace! for successful cases and error! for failures is appropriate.

Consider using a consistent style for the path field in both arms of the match:

 match abs_path.to_str() {
     Some(s) => trace!(path = s, "Writing to path"),
-    None => error!(path=?abs_path, "Cannot parse path"),
+    None => error!(path = ?abs_path, "Cannot parse path"),
 }

This change adds a space after = in the None arm, matching the style in the Some arm.


Line range hint 1-28: Overall: Excellent implementation of structured logging.

The changes in this file successfully implement the PR objective of replacing println with tracing::xxxx() logging methods. The additions enhance the logging capabilities of the write_file_with_dirs function without altering its core functionality. These improvements will significantly aid in debugging and monitoring.

Key improvements:

  1. Added appropriate imports for tracing.
  2. Implemented structured logging for the file path being written.
  3. Added error logging for cases where the path can't be parsed.
  4. Replaced println! with trace! for successful file writes.

The suggested minor improvements (consistent formatting and safer path handling) will further enhance the robustness of the logging implementation.

Consider applying similar logging improvements consistently across the codebase to maintain a uniform approach to logging and error handling.

packages/ciphernode/enclave/src/bin/aggregator.rs (2)

22-22: LGTM with suggestions: Tracing subscriber initialized

The tracing subscriber is correctly initialized, which is necessary for the tracing macros to function. However, consider the following suggestions:

  1. Configure log levels, possibly based on environment (e.g., debug level for development, info for production).
  2. Consider allowing configuration of output destinations (e.g., stdout, file) based on runtime parameters.

Example:

let subscriber = tracing_subscriber::FmtSubscriber::builder()
    .with_max_level(tracing::Level::INFO)
    .finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");

Line range hint 1-33: Summary: Tracing successfully implemented

The changes in this file successfully implement the tracing crate for improved logging:

  1. The necessary import for tracing::info has been added.
  2. The tracing subscriber is initialized, enabling the use of tracing macros.
  3. The println! macro has been replaced with the info! macro from tracing.

These changes align well with the PR objectives and enhance the logging capabilities of the application. Consider the earlier suggestion about configuring log levels and output destinations for even more flexibility.

To further improve the logging architecture:

  1. Consider creating a separate logging module to centralize logging configuration.
  2. Implement different log levels (debug, warn, error) throughout the application for more granular logging.
  3. Add context to log messages where appropriate, such as including relevant variable values or system state.
packages/ciphernode/test_helpers/src/public_key_writer.rs (2)

32-32: LGTM: Improved logging with structured format.

The replacement of println! with info! enhances the logging mechanism by using structured logging. This change aligns well with the PR objectives and improves the overall logging quality.

Consider adding more context to the log message:

info!(path = &self.path, "Writing aggregated public key to file");

This provides slightly more information about what type of public key is being written.


Line range hint 1-34: Overall: Good improvement in logging, consider extending throughout the file.

The changes successfully implement structured logging using the tracing crate, which aligns with the PR objectives. This improves log quality and parseability without affecting the core functionality of the PublicKeyWriter.

For consistency, consider updating other potential logging statements in this file (if any) to use the tracing crate. Also, it might be beneficial to add debug-level logging for other significant operations in the PublicKeyWriter, such as when it's attached to the event bus.

Example:

pub fn attach(path: &str, bus: Addr<EventBus>) -> Addr<Self> {
    let addr = Self {
        path: path.to_owned(),
    }
    .start();
    bus.do_send(Subscribe {
        listener: addr.clone().recipient(),
        event_type: "PublicKeyAggregated".to_string(),
    });
    debug!(path = path, "PublicKeyWriter attached to event bus");
    addr
}

This would provide a more comprehensive logging coverage for the PublicKeyWriter operations.

packages/ciphernode/test_helpers/src/plaintext_writer.rs (1)

34-34: LGTM: Improved logging with structured fields.

The replacement of println! with info! successfully implements the PR's objective. The use of a structured field (path) enhances the log's informativeness, making it easier to filter and analyze logs.

A minor suggestion for improvement:

Consider adding the output.len() to the log message to provide more context. This could be helpful for debugging or monitoring purposes. Here's a suggested modification:

info!(path = &self.path, output_length = output.len(), "Writing Plaintext To Path");
packages/ciphernode/enclave/src/main.rs (2)

33-33: LGTM: Tracing subscriber initialized, consider error handling

The initialization of the tracing subscriber is correctly placed at the beginning of the main function. This sets up the logging infrastructure as intended.

Consider adding error handling for the initialization:

tracing_subscriber::fmt::init().expect("Failed to initialize tracing");

This will provide more informative feedback if the initialization fails.


38-38: LGTM: Println replaced with info! macro

The replacement of println! with info! for logging the ciphernode launch is correct and aligns with the PR objective. This change enhances logging by using structured logging.

For consistency with typical log messages, consider changing the log message to lowercase:

info!("Launching ciphernode: ({})", address);

This follows common logging conventions where only the first letter is capitalized.

packages/ciphernode/router/src/ciphernode_selector.rs (2)

55-55: Consider using into() instead of clone().

The change to clone address when passing it to GetHasNode is good for ownership. However, for a small optimization, consider using address.into() instead of address.clone(). This allows for a potentially more efficient conversion if address is already owned.

-                    address: address.clone(),
+                    address: address.into(),

61-61: LGTM: Informative log message added.

The addition of this log message aligns well with the PR objective of enhancing logging functionality. It provides valuable information about ciphernode selection, which can aid in debugging and monitoring.

Consider adding more context to the log message:

-                    info!(node = address, "Ciphernode was not selected");
+                    info!(node = address, seed = seed, size = size, "Ciphernode was not selected for committee");

This change would provide more context about the selection process, including the seed and committee size.

packages/ciphernode/evm/src/helpers.rs (1)

35-41: LGTM: Logging statements added effectively

The new logging statements enhance the observability of the stream_from_evm function without altering its core functionality. They provide valuable insights into the log processing flow.

Suggestion for improvement:
Consider adding more context to the log messages. For example:

-trace!("Received log from EVM");
+trace!("Received log from EVM: {:?}", log);

-trace!("Failed to extract log from EVM");
+trace!("Failed to extract log from EVM: {:?}", log);

-info!("Extracted log from evm sending now.");
+info!("Extracted log from EVM, sending event: {:?}", event);

This additional context could be valuable for debugging and monitoring.

packages/ciphernode/evm/src/enclave_sol_writer.rs (1)

97-97: Approved: Improved logging with structured format

The replacement of println! with info! and the use of a structured logging format is a significant improvement. This change aligns perfectly with the PR objective and enhances the logging mechanism.

Consider adding a more descriptive message to provide context:

-info!(tx=%receipt.transaction_hash, "tx")
+info!(tx=%receipt.transaction_hash, "Transaction published successfully")

This change would make the log message more informative and easier to understand at a glance.

packages/ciphernode/evm/src/registry_filter_sol.rs (1)

96-96: Approved: Enhanced logging with tracing

The replacement of println! with info! from the tracing crate is a good improvement. It provides structured logging, which is more suitable for production environments and easier to parse programmatically.

A minor suggestion to improve clarity:

Consider adding a more descriptive message to the log. For example:

info!(tx=%receipt.transaction_hash, "Committee published successfully");

This provides more context about what the transaction represents.

packages/ciphernode/router/src/hooks.rs (3)

40-42: LGTM: Improved error handling for LazyKeyshare

The addition of error handling for the missing fhe instance is a good improvement. It provides clear feedback when key generation cannot proceed due to missing dependencies.

Consider extracting the error message to a constant for easier maintenance and potential reuse:

const ERR_MSG_FHE_NOT_SET: &str = "Could not create Keyshare because the fhe instance it depends on was not set on the context.";

// Then use it in the error reporting:
bus.err(EnclaveErrorType::KeyGeneration, anyhow!(ERR_MSG_FHE_NOT_SET));

59-64: LGTM: Enhanced error handling for LazyPlaintextAggregator

The addition of error handling for missing fhe and meta instances is a good improvement. It provides clear feedback when plaintext aggregation cannot proceed due to missing dependencies.

For consistency with the previous suggestion, consider extracting the error messages to constants:

const ERR_MSG_FHE_NOT_SET_PLAINTEXT: &str = "Could not create PlaintextAggregator because the fhe instance it depends on was not set on the context.";
const ERR_MSG_META_NOT_SET_PLAINTEXT: &str = "Could not create PlaintextAggregator because the meta instance it depends on was not set on the context.";

// Then use them in the error reporting:
bus.err(EnclaveErrorType::PlaintextAggregation, anyhow!(ERR_MSG_FHE_NOT_SET_PLAINTEXT));
bus.err(EnclaveErrorType::PlaintextAggregation, anyhow!(ERR_MSG_META_NOT_SET_PLAINTEXT));

94-99: LGTM: Improved error handling for LazyPublicKeyAggregator

The addition of error handling for missing fhe and meta instances is a good improvement. It provides clear feedback when public key aggregation cannot proceed due to missing dependencies.

For consistency with the previous suggestions, consider extracting the error messages to constants:

const ERR_MSG_FHE_NOT_SET_PUBLICKEY: &str = "Could not create PublicKeyAggregator because the fhe instance it depends on was not set on the context.";
const ERR_MSG_META_NOT_SET_PUBLICKEY: &str = "Could not create PublicKeyAggregator because the meta instance it depends on was not set on the context.";

// Then use them in the error reporting:
bus.err(EnclaveErrorType::PublickeyAggregation, anyhow!(ERR_MSG_FHE_NOT_SET_PUBLICKEY));
bus.err(EnclaveErrorType::PublickeyAggregation, anyhow!(ERR_MSG_META_NOT_SET_PUBLICKEY));

Consider refactoring the error checking logic for fhe and meta instances into a separate function to reduce code duplication between LazyPlaintextAggregator::create and LazyPublicKeyAggregator::create. For example:

fn check_dependencies(ctx: &Context, bus: &Addr<EventBus>, error_type: EnclaveErrorType) -> Result<(), ()> {
    if ctx.fhe.is_none() {
        bus.err(error_type, anyhow!("Could not create aggregator because the fhe instance it depends on was not set on the context."));
        return Err(());
    }
    if ctx.meta.is_none() {
        bus.err(error_type, anyhow!("Could not create aggregator because the meta instance it depends on was not set on the context."));
        return Err(());
    }
    Ok(())
}

// Then use it in both create methods:
if check_dependencies(ctx, &bus, EnclaveErrorType::PlaintextAggregation).is_err() {
    return;
}

This refactoring would make the code more maintainable and reduce the risk of inconsistencies between similar error handling blocks.

packages/ciphernode/evm/src/enclave_sol_reader.rs (2)

59-61: Enhance error message for E3Requested parsing

The use of error! macro is appropriate for logging parsing errors. However, consider enhancing the error message to provide more context:

- error!("Error parsing event E3Requested after topic matched!");
+ error!("Failed to parse E3Requested event: {:?}", data);

This change would log the actual data that failed to parse, aiding in debugging efforts.


72-76: LGTM: Trace logging for unknown events (with minor typo)

The addition of trace! logging for unknown events is a good practice. It provides visibility into unexpected events without cluttering logs at higher severity levels.

There's a small typo in the log message:

- "Unknown event was received by Enclave.sol parser buut was ignored"
+ "Unknown event was received by Enclave.sol parser but was ignored"
packages/ciphernode/evm/src/ciphernode_registry_sol.rs (4)

11-11: LGTM! Consider grouping related imports.

The addition of the tracing crate import aligns well with the PR objective of enhancing logging functionality. The specific macros imported (error, info, trace) suggest a structured approach to logging at different levels, which is a good practice.

Consider grouping related imports together. You could move this import closer to other external crate imports for better organization.


73-75: LGTM! Consider adding more context to the error log.

The replacement of println! with the error! macro from tracing is a good improvement, aligning with the PR objectives. This change enhances the logging structure and will likely improve error tracking and debugging.

Consider adding more context to the error log, such as including the data that failed to parse. This could help with debugging in the future. For example:

error!("Error parsing event CiphernodeAdded after topic was matched. Data: {:?}", data);

81-83: LGTM! Consider adding more context to the error log.

The replacement of println! with the error! macro from tracing is consistent with the previous change and aligns well with the PR objectives. This change contributes to a more structured and effective logging system.

Similar to the previous suggestion, consider adding more context to the error log by including the data that failed to parse. For example:

error!("Error parsing event CiphernodeRemoved after topic was matched. Data: {:?}", data);

87-91: LGTM! Minor typo in the log message.

The addition of the trace! macro for logging unknown events is a good improvement. It enhances the traceability of event handling without cluttering logs with potentially frequent occurrences of unknown events. The use of trace! level is appropriate for this kind of information.

There's a minor typo in the log message. "buut" should be "but":

trace!(
    topic=?_topic,
    "Unknown event was received by Enclave.sol parser but was ignored"
);
tests/basic_integration/test.sh (2)

15-15: LGTM! Consider making the log level configurable.

The addition of export RUST_LOG=info aligns well with the PR objectives of enhancing logging functionality. This will enable more detailed logging for Rust components during test execution.

To improve flexibility, consider making the log level configurable:

-export RUST_LOG=info
+export RUST_LOG=${RUST_LOG:-info}

This change allows overriding the log level when running the script, while maintaining "info" as the default.


Line range hint 1-168: Consider adding bash logging statements for improved debugging.

While the RUST_LOG environment variable has been set for Rust components, adding some bash logging statements throughout this script could further enhance debugging capabilities during integration testing.

Here's an example of how you could add logging to key sections of the script:

log_info() {
    echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# Add this function near the top of the script

# Then use it throughout the script, for example:
log_info "Starting EVM node"
yarn evm:node &

log_info "Launching ciphernode $CIPHERNODE_ADDRESS_1"
yarn ciphernode:launch --address $CIPHERNODE_ADDRESS_1 --config "$SCRIPT_DIR/lib/ciphernode_config.yaml" &

# ... and so on for other key operations

This will provide a consistent logging format for bash operations, complementing the Rust logging.

🧰 Tools
🪛 Shellcheck

[warning] 18-18: RPC_URL appears unused. Verify use (or export if used externally).

(SC2034)

packages/ciphernode/aggregator/src/plaintext_aggregator.rs (3)

128-128: LGTM: Replaced println! with structured logging

The changes successfully replace println! statements with error! macros from the tracing crate, aligning with the PR objectives. This enhances the logging mechanism by providing structured logs instead of simple console output.

Minor suggestion: Consider adding more context to the error messages, such as including the e3_id in the log when the wrong ID is sent to the aggregator. This could further improve debuggability.

Example:

error!(?e3_id, expected_e3_id = ?act.e3_id, "Wrong e3_id sent to aggregator. This should not happen.");

Also applies to: 148-148, 153-153


Line range hint 64-64: LGTM: Improved add_share method return type

The change to return Result<PlaintextAggregatorState> instead of Result<()> is a good improvement. It provides more information about the aggregator's state after adding a share, allowing callers to react to state changes more effectively.

Suggestion: Consider using the ? operator for error propagation instead of early returns. This can make the code more concise and consistent with Rust's error handling patterns.

Example:

pub fn add_share(&mut self, share: Vec<u8>) -> Result<PlaintextAggregatorState> {
    let PlaintextAggregatorState::Collecting {
        threshold_m,
        shares,
        ciphertext_output,
        ..
    } = &mut self.state else {
        return Err(anyhow::anyhow!("Can only add share in Collecting state"));
    };

    shares.insert(share);
    Ok(if shares.len() == *threshold_m {
        PlaintextAggregatorState::Computing {
            shares: shares.clone(),
            ciphertext_output: ciphertext_output.to_vec(),
        }
    } else {
        self.state.clone()
    })
}

Also applies to: 65-65, 66-66, 67-67, 68-68, 69-69, 70-70, 71-71, 72-72, 73-73, 74-74, 75-75, 76-76, 77-77, 78-78, 79-79, 80-80, 81-81, 82-82, 83-83, 84-84


Line range hint 86-86: LGTM: Improved set_decryption method return type

The change to return Result<PlaintextAggregatorState> instead of Result<()> is consistent with the improvements made to the add_share method. This provides better visibility into the aggregator's state after setting the decryption.

Suggestion: For consistency with the add_share method, consider handling the case where the state is not Computing more explicitly:

pub fn set_decryption(&mut self, decrypted: Vec<u8>) -> Result<PlaintextAggregatorState> {
    let PlaintextAggregatorState::Computing { shares, .. } = &mut self.state else {
        return Err(anyhow::anyhow!("Can only set decryption in Computing state"));
    };

    let shares = shares.to_owned();
    Ok(PlaintextAggregatorState::Complete { decrypted, shares })
}

This change would make the error handling more explicit and consistent across both methods.

Also applies to: 87-87, 88-88, 89-89, 90-90, 91-91, 92-92, 93-93, 94-94, 95-95

packages/ciphernode/aggregator/src/publickey_aggregator.rs (4)

136-136: LGTM: Improved logging with structured format

The replacement of println! with error! enhances logging capabilities as intended. The inclusion of the state in the log message provides valuable context.

Consider adding a static string identifier to make log filtering easier:

error!(event = "aggregator_closed", state = ?self.state, "Aggregator has been closed for collecting keyshares.");

158-158: Approved: Logging improved, but could be more informative

The replacement of println! with error! is good. However, the log message could be more informative.

Consider adding more context:

error!(event = "node_not_in_committee", address = ?address, "Node not found in committee");

This addition provides more details about which node was not found, making debugging easier.


163-163: Approved: Logging improved, but could be more detailed

The switch to error! is good. However, for unexpected scenarios like this, more detailed logging would be beneficial.

Consider enhancing the log message:

error!(
    event = "wrong_e3_id",
    expected_e3_id = ?act.e3_id,
    received_e3_id = ?e3_id,
    "Incorrect e3_id sent to aggregator. This indicates a potential bug or security issue."
);

This provides more context about the mismatch and emphasizes the severity of the situation.


Line range hint 1-238: Summary: Logging improvements successfully implemented

The changes in this file successfully replace println! statements with tracing::error! calls, aligning with the PR objectives. These improvements enhance the ability to debug and monitor the application by providing structured logging.

Consider reviewing the entire file for other locations where similar logging improvements could be applied, especially for important events or error conditions. This would ensure consistency in logging practices throughout the PublicKeyAggregator implementation.

packages/ciphernode/core/src/events.rs (3)

186-201: Approve the new get_data method with a minor suggestion

The new get_data method provides a consistent way to get a string representation of the event data, which is excellent for logging and debugging purposes. It leverages the Display trait implementations of the inner data structures, promoting code reuse.

Consider handling the default case explicitly instead of commenting it out. You could either remove the comment or implement a default case:

 pub fn get_data(&self) -> String {
     match self.clone() {
         EnclaveEvent::KeyshareCreated { data, .. } => format!("{}", data),
         EnclaveEvent::E3Requested { data, .. } => format!("{}", data),
         EnclaveEvent::PublicKeyAggregated { data, .. } => format!("{}", data),
         EnclaveEvent::CiphertextOutputPublished { data, .. } => format!("{}", data),
         EnclaveEvent::DecryptionshareCreated { data, .. } => format!("{}", data),
         EnclaveEvent::PlaintextAggregated { data, .. } => format!("{}", data),
         EnclaveEvent::CiphernodeSelected { data, .. } => format!("{}", data),
         EnclaveEvent::CiphernodeAdded { data, .. } => format!("{}", data),
         EnclaveEvent::CiphernodeRemoved { data, .. } => format!("{}", data),
         EnclaveEvent::E3RequestComplete { data, .. } => format!("{}", data),
         EnclaveEvent::EnclaveError { data, .. } => format!("{:?}", data),
-        // _ => "<omitted>".to_string(),
+        _ => "<unknown event>".to_string(),
     }
 }

This ensures that all possible cases are handled explicitly.


330-334: Approve new Display implementations with a suggestion for consistency

The new Display implementations for various structs greatly enhance the readability of logs and debug outputs. They provide a consistent format for representing the data of different event types.

For consistency, consider using the same format for all structs. Some implementations use <omitted> for sensitive or large fields, while others simply exclude them. Standardize this approach across all implementations. For example:

 impl Display for PublicKeyAggregated {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(
             f,
-            "e3_id: {}, src_chain_id: {}, nodes: <omitted>, pubkey: <omitted>",
-            self.e3_id, self.src_chain_id,
+            "e3_id: {}, src_chain_id: {}, nodes: <omitted>, pubkey: <omitted>",
+            self.e3_id, self.src_chain_id
         )
     }
 }

Apply this consistently to all Display implementations where applicable.

Also applies to: 344-348, 359-367, 379-386, 396-404, 413-417, 427-435, 444-448, 458-466, 476-484, 493-497, 502-506


376-377: Approve retention of src_chain_id with a suggestion for documentation

The decision to keep the src_chain_id field in the E3Requested struct has been finalized, as evidenced by the removal of comments indicating potential future modifications.

Consider adding a brief documentation comment to explain the purpose and significance of the src_chain_id field. This will help future developers understand its role in the E3 request process. For example:

 pub struct E3Requested {
     pub e3_id: E3id,
     pub threshold_m: usize,
     pub seed: Seed,
     pub params: Vec<u8>,
+    /// Identifier of the source chain initiating the E3 request
     pub src_chain_id: u64,
 }
packages/ciphernode/sortition/src/sortition.rs (1)

Line range hint 52-53: Handle parsing errors instead of using .unwrap()

Using .unwrap() on b.parse() can cause the program to panic if the parsing fails. It's better to handle the potential error to make the code more robust.

Here's how you can handle the parsing errors:

-             // TODO: error handling
-             .map(|b| b.parse().unwrap())
-             .collect();
+             .map(|b| {
+                 b.parse().map_err(|e| anyhow!("Failed to parse address {}: {}", b, e))
+             })
+             .collect::<Result<Vec<_>>>()?;

This modification propagates the parsing errors properly, allowing the calling function to handle them as needed.

packages/ciphernode/p2p/src/p2p.rs (3)

12-12: Correct the typo in the documentation comment.

In the documentation comment, 'EVentBus' should be 'EventBus'.


Line range hint 65-72: Avoid using unwrap() inside asynchronous tasks.

Using unwrap() inside tokio::spawn can cause the task to panic if an error occurs. To prevent unexpected panics, handle the error explicitly.

Apply this diff to handle the potential error:

 tokio::spawn(async move { 
-    libp2p.start().await.unwrap() 
+    if let Err(e) = libp2p.start().await {
+        error!("Error starting libp2p: {:?}", e);
+        // Consider additional error handling here
+    }
 });

105-105: Consider adjusting the logging level from trace! to debug!.

The trace! macro is used for very detailed diagnostic information. If these messages are intended for standard debugging, using debug! may be more appropriate to avoid excessive verbosity in the logs.

Also applies to: 111-111

packages/ciphernode/p2p/src/libp2p_router.rs (4)

Line range hint 114-129: Avoid using .unwrap() without checking for None

The method start contains multiple instances of .unwrap() on self.swarm and self.topic. Using .unwrap() can lead to a panic if these options are None. It's safer to handle the None case explicitly.

Consider refactoring to handle None values gracefully:

pub async fn start(&mut self) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
    if let (Some(swarm), Some(topic)) = (self.swarm.as_mut(), self.topic.as_ref()) {
        swarm.listen_on("/ip4/0.0.0.0/udp/0/quic-v1".parse()?)?;
        swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
        loop {
            select! {
                Some(line) = self.cmd_rx.recv() => {
                    if let Err(e) = swarm.behaviour_mut().gossipsub.publish(topic.clone(), line) {
                        error!(error = ?e, "Error publishing line to swarm");
                    }
                }
                event = swarm.select_next_some() => match event {
                    // ... rest of the event handling ...
                }
            }
        }
    } else {
        return Err("Swarm or topic not initialized".into());
    }
}

Line range hint 136-158: Consider adjusting log levels for better visibility

Currently, events like peer discovery and message reception are logged using trace!. Depending on your logging strategy, you might want to use debug! or info! to make these logs more visible during normal operation.


114-116: Enhance documentation for the start method

The comment /// Listen on the default multiaddr is brief. Expanding the documentation can help other developers understand the method's purpose and usage.

Consider updating the documentation:

/// Starts the `EnclaveRouter`, listening on the default multiaddresses and processing incoming commands and swarm events.
/// 
/// This method sets up listeners for both QUIC and TCP transports,
/// handles publishing messages received from `cmd_rx`,
/// and processes various swarm events such as new peers discovered via mDNS.
/// 
/// # Errors
///
/// Returns an error if the swarm fails to listen on the specified addresses or if message handling encounters an issue.

Line range hint 114-129: Use specific error types instead of Box<dyn Error>

Returning Box<dyn Error + Send + Sync + 'static> erases the concrete error types, making error handling less precise. Consider defining a custom error type or using a specific error enum to improve clarity.

Define a custom error enum:

#[derive(Debug, thiserror::Error)]
pub enum EnclaveRouterError {
    #[error("Swarm or topic not initialized")]
    Uninitialized,
    #[error("IO error")]
    Io(#[from] io::Error),
    #[error("Gossipsub error")]
    Gossipsub(#[from] gossipsub::error::PublishError),
    // ... other error variants ...
}

Update the method signature:

pub async fn start(&mut self) -> Result<(), EnclaveRouterError> {
    // ... method implementation ...
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6d81034 and eb94fcc.

⛔ Files ignored due to path filters (1)
  • packages/ciphernode/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (30)
  • packages/ciphernode/aggregator/Cargo.toml (1 hunks)
  • packages/ciphernode/aggregator/src/plaintext_aggregator.rs (3 hunks)
  • packages/ciphernode/aggregator/src/publickey_aggregator.rs (3 hunks)
  • packages/ciphernode/core/src/events.rs (12 hunks)
  • packages/ciphernode/enclave/Cargo.toml (1 hunks)
  • packages/ciphernode/enclave/src/bin/aggregator.rs (2 hunks)
  • packages/ciphernode/enclave/src/main.rs (2 hunks)
  • packages/ciphernode/enclave_node/src/main.rs (0 hunks)
  • packages/ciphernode/evm/Cargo.toml (1 hunks)
  • packages/ciphernode/evm/src/ciphernode_registry_sol.rs (3 hunks)
  • packages/ciphernode/evm/src/enclave_sol_reader.rs (3 hunks)
  • packages/ciphernode/evm/src/enclave_sol_writer.rs (2 hunks)
  • packages/ciphernode/evm/src/helpers.rs (2 hunks)
  • packages/ciphernode/evm/src/registry_filter_sol.rs (2 hunks)
  • packages/ciphernode/keyshare/src/keyshare.rs (0 hunks)
  • packages/ciphernode/logger/Cargo.toml (1 hunks)
  • packages/ciphernode/logger/src/logger.rs (3 hunks)
  • packages/ciphernode/p2p/src/libp2p_router.rs (5 hunks)
  • packages/ciphernode/p2p/src/p2p.rs (5 hunks)
  • packages/ciphernode/router/Cargo.toml (1 hunks)
  • packages/ciphernode/router/src/ciphernode_selector.rs (2 hunks)
  • packages/ciphernode/router/src/hooks.rs (4 hunks)
  • packages/ciphernode/sortition/Cargo.toml (1 hunks)
  • packages/ciphernode/sortition/src/sortition.rs (6 hunks)
  • packages/ciphernode/test_helpers/Cargo.toml (1 hunks)
  • packages/ciphernode/test_helpers/src/plaintext_writer.rs (2 hunks)
  • packages/ciphernode/test_helpers/src/public_key_writer.rs (2 hunks)
  • packages/ciphernode/test_helpers/src/utils.rs (3 hunks)
  • packages/ciphernode/tests/tests/test_aggregation_and_decryption.rs (0 hunks)
  • tests/basic_integration/test.sh (1 hunks)
💤 Files with no reviewable changes (3)
  • packages/ciphernode/enclave_node/src/main.rs
  • packages/ciphernode/keyshare/src/keyshare.rs
  • packages/ciphernode/tests/tests/test_aggregation_and_decryption.rs
🧰 Additional context used
🔇 Additional comments (37)
packages/ciphernode/aggregator/Cargo.toml (1)

13-13: LGTM: Addition of tracing dependency aligns with PR objectives.

The addition of the tracing crate as a workspace dependency is consistent with the PR's goal of enhancing logging functionality. This change will enable the use of structured logging in the aggregator package, which can significantly improve debugging and monitoring capabilities.

The use of workspace-level version management ({ workspace = true }) is also consistent with other dependencies in this file, ensuring proper version coordination across the project.

packages/ciphernode/evm/Cargo.toml (1)

15-15: LGTM: Addition of tracing crate aligns with PR objectives.

The addition of the tracing crate as a workspace dependency is appropriate and aligns well with the PR objectives. This change will enable the replacement of println statements with more structured logging methods provided by the tracing crate, enhancing the project's logging capabilities.

Using { workspace = true } is a good practice as it ensures consistent versioning across the workspace.

packages/ciphernode/router/Cargo.toml (1)

14-15: LGTM! The changes align well with the PR objectives.

The addition of tracing and anyhow as dependencies is a positive step towards improving the logging and error handling capabilities of the router package. These changes directly support the PR's goal of enhancing the logging functionality.

  • tracing: This addition aligns perfectly with the objective of replacing println with more sophisticated logging methods.
  • anyhow: While not explicitly mentioned in the PR objectives, this is a valuable addition for improved error handling, which complements well with enhanced logging.

Both dependencies are specified to use the workspace version, ensuring consistency across the project.

packages/ciphernode/test_helpers/src/utils.rs (1)

3-3: LGTM: Tracing import added as per PR objective.

The import of error and trace from the tracing crate aligns with the PR's goal to enhance logging functionality.

packages/ciphernode/enclave/src/bin/aggregator.rs (2)

4-4: LGTM: Tracing import added correctly

The import of tracing::info is correctly added, which aligns with the PR objective of enhancing logging functionality.


24-24: LGTM: Println replaced with info logging

The println! macro has been correctly replaced with the info! macro from tracing. This change aligns perfectly with the PR objective and improves the logging mechanism.

packages/ciphernode/test_helpers/src/public_key_writer.rs (1)

4-4: LGTM: Appropriate import for tracing.

The addition of use tracing::info; is in line with the PR objectives to enhance logging functionality. This import enables the use of structured logging via the tracing crate.

packages/ciphernode/test_helpers/src/plaintext_writer.rs (2)

4-4: LGTM: Import of tracing::info aligns with PR objectives.

The addition of use tracing::info; is in line with the PR's goal to enhance logging functionality. This import enables the use of structured logging, which will improve the application's debugging and monitoring capabilities.


Line range hint 1-42: Overall: Successful implementation of improved logging.

The changes in this file successfully implement the PR objectives by replacing println! with tracing::info!. This enhancement improves the logging capabilities of the PlaintextWriter struct without altering its core functionality.

Please ensure that any tests relying on stdout output (if any) are updated to accommodate this change in logging mechanism. Run the following script to check for any tests that might need updating:

If the script returns any results, please review those test files and update them accordingly.

packages/ciphernode/enclave/src/main.rs (1)

5-5: LGTM: Tracing import added correctly

The addition of use tracing::info; is appropriate and aligns with the PR objective of enhancing logging functionality.

packages/ciphernode/router/src/ciphernode_selector.rs (2)

6-6: LGTM: Import statement for tracing module.

The addition of the tracing::info import aligns with the PR objective of enhancing logging functionality. It's correctly placed and properly formatted.


Line range hint 1-72: Overall assessment: Changes align well with PR objectives.

The modifications in this file successfully implement the tracing crate for improved logging, which is consistent with the PR's main objective. The added log message provides valuable information about ciphernode selection, enhancing the debugging and monitoring capabilities of the system.

A few minor suggestions have been made to further optimize the code and improve the logging output. These changes, while not critical, could provide additional benefits in terms of performance and log clarity.

packages/ciphernode/evm/src/helpers.rs (2)

18-18: LGTM: Tracing import added correctly

The import of tracing::{info, trace} is correctly added and aligns with the PR objective of enhancing logging functionality.


Line range hint 1-124: Summary: Effective implementation of logging

The changes in this file successfully implement the PR objective of enhancing logging functionality. The tracing crate is correctly imported and used to add strategic log points within the stream_from_evm function. These additions improve the observability of the EVM log processing without altering the core logic.

The log levels are appropriately chosen, with trace for detailed debugging and info for significant operational events. This implementation will greatly aid in debugging and monitoring the application's interaction with the EVM.

Overall, these changes represent a positive improvement to the codebase.

packages/ciphernode/evm/src/enclave_sol_writer.rs (2)

16-16: LGTM: New import for structured logging

The addition of use tracing::info; aligns with the PR objective of enhancing logging functionality. This import enables the use of structured logging, which will improve the overall logging mechanism in the codebase.


Line range hint 1-124: Summary: Successful implementation of structured logging

The changes in this file successfully implement structured logging using the tracing crate, which aligns with the PR objectives. The replacement of println! with info! and the use of key-value pairs in the log message enhance the logging mechanism, making it more informative and easier to parse.

These improvements will facilitate better debugging and monitoring of the application, particularly for transaction-related events. The core functionality of the EnclaveSolWriter remains unchanged, ensuring that the existing behavior is preserved while enhancing the logging capabilities.

packages/ciphernode/evm/src/registry_filter_sol.rs (2)

15-15: LGTM: New import for tracing

The addition of use tracing::info; is in line with the PR objective to enhance logging functionality. This import will allow the use of structured logging via the tracing crate.


Line range hint 1-140: Summary: Successful implementation of tracing for improved logging

The changes in this file successfully implement the tracing crate for improved logging, which aligns with the PR objectives. The modifications include:

  1. Adding the necessary import for tracing::info.
  2. Replacing a println! statement with a structured log using info!.

These changes enhance the logging mechanism by providing more structured and easily parseable logs, which is beneficial for debugging and monitoring in production environments. The core functionality of the code remains unchanged, ensuring that this is a non-breaking improvement to the codebase.

Great job on implementing this logging enhancement!

packages/ciphernode/router/src/hooks.rs (2)

4-4: LGTM: Import changes align with PR objectives

The addition of anyhow::anyhow and the expanded import from enclave_core are consistent with the PR's goal of enhancing error handling and logging. These imports provide the necessary tools for implementing the improved error reporting throughout the file.

Also applies to: 6-6


Line range hint 1-114: Overall assessment: Approved with minor suggestions

The changes in this file successfully implement improved error handling and logging, aligning well with the PR objectives. The modifications consistently enhance the robustness of the code by providing clear error messages when dependencies are missing.

Key improvements:

  1. Consistent use of bus.err for error reporting.
  2. Clear and informative error messages.
  3. Proper use of anyhow! macro for error creation.

Suggestions for further improvement:

  1. Extract error messages to constants for better maintainability.
  2. Consider refactoring common error checking logic into a separate function to reduce code duplication.

These changes significantly enhance the debugging capabilities of the codebase. Great job on improving the overall quality and maintainability of the code!

packages/ciphernode/evm/src/enclave_sol_reader.rs (3)

10-10: LGTM: Tracing import added for improved logging

The addition of the tracing crate with error, info, and trace macros aligns well with the PR objective of enhancing logging functionality. This change provides a good range of log levels for more structured and informative logging.


112-112: LGTM: Improved logging in attach method

The replacement of println! with info! and the addition of a structured field for the address is a significant improvement. This change enhances the logging quality and aligns with the PR's objective.


Line range hint 1-134: Overall assessment: Successful implementation of structured logging

The changes in this file consistently improve the logging mechanism by replacing println! statements with structured logging using the tracing crate. This aligns perfectly with the PR's objective of enhancing logging functionality.

Key improvements:

  1. Appropriate use of different log levels (error, info, trace).
  2. Addition of structured fields in log messages for better context.
  3. Consistent approach to error handling and logging across the file.

These changes will significantly improve debugging and monitoring capabilities in the application. Great job on implementing these improvements!

packages/ciphernode/evm/src/ciphernode_registry_sol.rs (2)

129-129: LGTM! Good use of structured logging.

The replacement of println! with the info! macro from tracing is a good improvement, consistent with the PR objectives. The use of a structured field for the address (address=%contract_address) is particularly noteworthy, as it enhances log parsing and filtering capabilities.


Line range hint 1-165: Overall, excellent improvements to logging functionality.

The changes in this file consistently enhance the logging capabilities by replacing println! statements with appropriate tracing macros. This aligns perfectly with the PR objectives and brings several benefits:

  1. Structured logging: The use of error!, info!, and trace! macros provides better structure to the logs.
  2. Log levels: Different log levels allow for more granular control over what gets logged in different environments.
  3. Improved error context: Error logs now provide clearer context about failures.
  4. Better traceability: The addition of trace logs for unknown events enhances the overall traceability of the system.

These improvements will significantly aid in debugging and monitoring the application. Great job on implementing these changes consistently throughout the file!

packages/ciphernode/aggregator/src/plaintext_aggregator.rs (1)

10-10: LGTM: Tracing crate import added

The addition of use tracing::error; aligns with the PR objective of enhancing logging functionality. This import will allow the use of structured logging instead of println! statements.

packages/ciphernode/aggregator/src/publickey_aggregator.rs (1)

9-9: LGTM: Tracing import added for structured logging

The addition of use tracing::error; is appropriate for implementing structured logging, which aligns with the PR objectives.

packages/ciphernode/core/src/events.rs (4)

318-318: Approve the updated Display implementation for EnclaveEvent

The modification to use the new get_data method in the Display implementation for EnclaveEvent is a good improvement. It ensures consistency in how event data is displayed and promotes code reuse.

This change aligns well with the new get_data method and will provide more informative and consistent log outputs.


Line range hint 1-582: Overall approval with minor suggestions for improvement

The changes made to this file significantly enhance the logging and debugging capabilities of the enclave system. The addition of Display implementations for various structs and the new get_data method in EnclaveEvent provide more consistent and informative event representations.

Key improvements:

  1. Enhanced event data representation through new Display implementations.
  2. Consistent event data retrieval with the get_data method.
  3. Updated EnclaveErrorType to include Sortition errors.

Suggestions for further improvement:

  1. Standardize the approach for omitting sensitive or large fields in Display implementations.
  2. Add brief documentation for the src_chain_id field in the E3Requested struct.
  3. Consider explicitly handling the default case in the get_data method of EnclaveEvent.

These changes align well with the PR objective of enhancing logging functionality. The transition from println to tracing::xxxx() methods is not directly visible in this file, but these changes support that goal by providing better structured data for logging.


542-542: Approve addition of Sortition variant with verification suggestion

The addition of the Sortition variant to the EnclaveErrorType enum is approved. This suggests that error handling for sortition-related issues has been introduced in the system.

To ensure this new error type is properly handled throughout the codebase, let's verify its usage:

#!/bin/bash
# Check for usage of the new Sortition error type
rg --type rust 'EnclaveErrorType::Sortition' -C 3

This will help us understand where and how the new error type is being used, and if any additional error handling might be needed in other parts of the codebase.


72-72: Consider the implications of shortening the EventId display format

The new format "evt:{base58_string[0..8]}" is more concise, which can improve log readability. However, it also reduces the uniqueness of the displayed EventId, potentially making it harder to distinguish between similar events in logs.

To assess the impact of this change, let's check for potential collisions:

This will help us understand if there are many EventIds generated in close proximity that might result in collisions when only the first 8 characters are used.

packages/ciphernode/logger/src/logger.rs (2)

3-3: Importing error and info macros

Adding error and info from the tracing crate is appropriate for enhanced logging functionality.


19-19: Logging readiness message with info! macro

Using info!(node=%name, "READY!"); effectively logs the node's readiness state.

packages/ciphernode/sortition/src/sortition.rs (1)

137-143: Clarify error handling in GetHasNode response

In the GetHasNode handler, when self.list.contains returns an Err, the error is sent to the bus, and false is returned. This could lead to situations where the caller cannot distinguish between a node not being present and an error occurring during the check.

Consider whether it's appropriate to return false on error, or if the error should be propagated or handled differently. If returning false is intentional, ensure that the callers are aware that false may indicate an error, not just the absence of the node. You might want to document this behavior clearly.

packages/ciphernode/p2p/src/libp2p_router.rs (3)

11-11: Approved: Correctly importing necessary tracing macros

The use of tracing::{error, info, trace}; imports the necessary macros for structured logging.


97-97: Approved: Logging default discovery type using info!

Replacing println! with info!("Defaulting to MDNS discovery") appropriately utilizes the tracing crate for logging.


130-130: Approved: Proper error logging when publishing fails

Logging the error with error!(error = ?e, "Error publishing line to swarm"); provides valuable debugging information.

packages/ciphernode/logger/Cargo.toml Outdated Show resolved Hide resolved
packages/ciphernode/test_helpers/src/utils.rs Show resolved Hide resolved
packages/ciphernode/enclave/src/main.rs Show resolved Hide resolved
packages/ciphernode/logger/src/logger.rs Show resolved Hide resolved
packages/ciphernode/logger/src/logger.rs Show resolved Hide resolved
packages/ciphernode/logger/src/logger.rs Show resolved Hide resolved
packages/ciphernode/sortition/src/sortition.rs Outdated Show resolved Hide resolved
packages/ciphernode/p2p/src/p2p.rs Show resolved Hide resolved
packages/ciphernode/p2p/src/libp2p_router.rs Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between eb94fcc and 81878f9.

📒 Files selected for processing (3)
  • packages/ciphernode/logger/Cargo.toml (1 hunks)
  • packages/ciphernode/p2p/src/p2p.rs (5 hunks)
  • packages/ciphernode/sortition/src/sortition.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/ciphernode/logger/Cargo.toml
  • packages/ciphernode/p2p/src/p2p.rs
🧰 Additional context used
🔇 Additional comments (3)
packages/ciphernode/sortition/src/sortition.rs (3)

20-20: LGTM: Improved error handling in contains method

The change to return Result<bool> instead of bool in the contains method signature enhances error handling capabilities, aligning with the PR objectives.


83-90: LGTM: Improved event bus integration

The addition of the bus field to the Sortition struct and the corresponding update to the new() constructor improve the structure for event handling. This change indirectly supports better logging capabilities.


95-95: LGTM: Consistent event bus initialization

The update to the attach method ensures that the event bus is properly passed to the Sortition instance, maintaining consistency with the changes made to the Sortition struct and its constructor.

@ryardley ryardley merged commit ecfd738 into main Oct 15, 2024
3 checks passed
This was referenced Oct 31, 2024
@ryardley ryardley deleted the ry/124-logging branch December 5, 2024 06:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Use proper logging
2 participants